package view;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import control.ControlMain;
import dao.Studentdao;
import entity.Student;

public class AddFrame extends JFrame implements ActionListener {

	/**
	 * 
	 */

	private static final long serialVersionUID = 1L;
	private JTextField[] jTextFields;
	private ControlMain cm;
	private Studentdao sd;

	public AddFrame() {

		setTitle("添加学生信息");
		setVisible(true);
		setLayout(null);
		setResizable(false);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setSize(450, 300);
		setLocationRelativeTo(null);
		Font font = new Font("幼圆", Font.BOLD, 15);
		String[] str = { "姓名：", "性别：" };
		JLabel[] label = new JLabel[str.length];
		jTextFields = new JTextField[str.length];
		for (int i = 0; i < str.length; i++) {
			label[i] = new JLabel(str[i]);
			label[i].setFont(font);
			label[i].setBounds(50, 40 + i * 50, 50, 50);
			add(label[i]);
			jTextFields[i] = new JTextField();
			jTextFields[i].setBounds(120, 40 + i * 60, 150, 30);
			add(jTextFields[i]);
		}
		String[] btstr = { "添加", "关闭", "返回" };
		JButton[] jbt = new JButton[btstr.length];
		for (int i = 0; i < btstr.length; i++) {
			jbt[i] = new JButton(btstr[i]);
			jbt[i].setSize(80, 40);
			jbt[i].setLocation(60 + i * 150, 200);
			jbt[i].addActionListener(this);
			add(jbt[i]);
		}
		sd = new Studentdao();
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String cmd = e.getActionCommand();
		if (cmd == "添加") {
			if (jTextFields[0].getText().trim().equals("") && jTextFields[1].getText().trim().equals("")) {
				JOptionPane.showMessageDialog(this, "请输入学生姓名和性别");
			} else {
				int f = JOptionPane.showConfirmDialog(this, "确认添加学生信息！", "提示信息", JOptionPane.YES_NO_OPTION);
				if (f == 0) {
					stuAdd();
					JOptionPane.showMessageDialog(this, "学生信息录入成功！");
				} else {
					JOptionPane.showMessageDialog(this, "你已取消录入该学生成绩！");
				}
			}
		}
		if (cmd == "关闭") {
			System.exit(0);
		}
		if (cmd == "返回") {
			this.setVisible(false);
			cm = new ControlMain();
			cm.setVisible(true);
		}
	}

	public void stuAdd() {
		Student s = new Student();
		s.setName(jTextFields[0].getText());
		s.setSex(jTextFields[1].getText());
		sd.Inserts(s);
	}

}
